/*********************************************************************************
 *      Copyright:  (C) 2025 Lijiahui<2199250859@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  get_temp.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(20/04/25)
 *         Author:  Lijiahui <2199250859@qq.com>
 *      ChangeLog:  1, Release initial version on "20/04/25 14:28:35"
 *                 
 ********************************************************************************/

#include "get_temp.h"

int ds18b20_get_temperature(float *tempe)
{
	DIR				*dirp;
	const char		*w1_path="/sys/bus/w1/devices/";	
	struct dirent	*direntp;
	int				found = 0;
	char 			ds_path[50];
	int	     		fd = -1;
	int				rv = -1;
	char 			*ptr = NULL;
	char 			chip[20];
	char     		buf[128];

	if( !tempe )
	{
		return -1;
	}

	/*find ds18b20 device nember*/
	if((dirp=opendir(w1_path)) == NULL)
	{
		log_warn("opendir error:5s\n", strerror(errno));
		return -2;
	}

	while((direntp = readdir(dirp)) != NULL)
	{
		if(strstr(direntp->d_name, "28-"))
		{
			strcpy(chip, direntp->d_name);
			found = 1;
			break;
		}
	}
	closedir(dirp);

	if(!found)
	{
		log_warn("Can not find ds118b20 in %s\n", w1_path);
		return -3;
	}

	//得到完整路径
	snprintf(ds_path, sizeof(ds_path), "%s/%s/w1_slave", w1_path, chip);
	
	//打开路径获取温度值
	if((fd = open(ds_path, O_RDONLY))<0)
	{
		log_warn("open %s error:%s\n", ds_path, strerror(errno));
		return -4;
	}
	
	memset(buf, 0, sizeof(buf));
	if(read(fd, buf, sizeof(buf)) < 0)
	{
		log_error("read %s error %s\n", ds_path, strerror(errno));
		rv = -5;
		goto cleanup;
	}
	ptr = strstr(buf, "t=");

	if(!ptr)
	{
		log_error("ERROR:can not get temperature\n");
		rv = -6;
		goto cleanup;
	}

	ptr += 2;

	*tempe = atof(ptr)/1000;
	
cleanup:
	close(fd);
	return rv;
}

//获取时间
int get_time(char *systime)
{
	time_t		rawtime;
	struct tm	*tim;

	time(&rawtime);//获取当前系统时间，并将其以秒数的形式存储到rawtime中
	tim = localtime(&rawtime);//将time_t类型时间值转换为可读的本地时间格式
	
	if(rawtime)
	{
		sprintf(systime, "%04d-%02d-%02d %02d:%02d:%02d", tim->tm_year+1900,
				tim->tm_mon+1, tim->tm_mday, tim->tm_hour, tim->tm_min, tim->tm_sec);

	}

	return 0;
}

int	get_devid(char *id, int len)
{
	int	sn = 1;

	snprintf(id, len, "RIP-%03d", sn);

	return 0;

	
}
	
